'use strict';
const {
	verifyToken
} = require('wx-common')
exports.main = async (event, context) => {
	const {
		userInfo,
		token
	} = event;

	const db = uniCloud.database();
	const dbCmd = db.command;
	const payload = verifyToken(token);

	if (payload.type === 1 || payload.type === 2) {
		// token验证通过
		const dbRes = await db.collection("user").where({
			openid: dbCmd.eq(payload.openid)
		}).update({
			nickName: userInfo.nickName,
			avatarUrl: userInfo.avatarUrl,
			gender: userInfo.gender,
			country: userInfo.country,
			province: userInfo.province,
			city: userInfo.city
		});

		const data = await db.collection("user").where({
			openid: dbCmd.eq(payload.openid)
		}).get();


		let resData = {
			userInfo: data.data[0]
		}

		delete resData.userInfo.openid;

		if (payload.type === 2) {
			// token即将过期返回新token
			resData.token = payload.newToken
		}

		return {
			code: 200,
			msg: '同步成功',
			data: resData
		};
	} else if (payload.type === 0) {
		// token验证失败 需重新登录
		return {
			code: 203,
			msg: '请重新登录',
			data: {}
		};
	}
};
